<template>
  <!-- el-breadcrumb 是 Element UI 提供的面包屑导航组件 -->
  <el-breadcrumb class="app-breadcrumb" separator-class="el-icon-arrow-right">
    <!-- transition-group 用于在切换面包屑项时添加过渡效果 -->
    <transition-group name="breadcrumb">
      <!-- 使用 v-for 遍历 levelList 中的数据，渲染面包屑项 -->
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <!-- 根据条件判断是否显示链接或只显示文本 -->
        <span v-if="item.redirect==='noRedirect'||index===levelList.length-1" class="no-redirect">{{
            item.meta.title
          }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
export default {
  data() {
    return {
      levelList: null // 存储面包屑数据
    }
  },
  watch: {
    $route(route) {
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb() // 监听路由变化，更新面包屑数据
    }
  },
  created() {
    this.getBreadcrumb() // 组件创建时初始化面包屑数据
  },
  methods: {
    getBreadcrumb() {
      // 过滤出具有 meta.title 属性的路由，构成面包屑的数据结构
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]

      // 如果不在首页，添加首页的面包屑项
      if (!this.isDashboard(first)) {
        matched = [{path: '/index', meta: {title: '首页'}}].concat(matched)
      }

      // 过滤掉不需要显示面包屑的路由项
      this.levelList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
    },
    isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'index'.toLocaleLowerCase()
    },
    pathCompile(path) {
      // 根据当前路由的参数动态编译出对应的路径
      const {params} = this.$route
      var pathToRegexp = require('path-to-regexp');
      var toPath = pathToRegexp.compile(path)
      return toPath(params)
    },
    handleLink(item) {
      const {redirect, path} = item
      if (redirect) {
        this.$router.push(redirect) // 处理重定向链接
        return
      }
      this.$router.push(this.pathCompile(path)) // 处理正常链接，根据参数编译路径
    }
  }
}
</script>

<style scoped>
/* 样式部分，仅在组件内生效 */
.app-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 40px;
  margin-left: 8px;
}

.no-redirect {
  color: #97a8be;
  cursor: text;
}

.el-breadcrumb__item {
  height: 40px;
}

/* 过渡效果样式 */
.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all .5s;
}

.breadcrumb-enter,
.breadcrumb-leave-active {
  opacity: 0;
  transform: translateX(20px);
}

.breadcrumb-move {
  transition: all .5s;
}

.breadcrumb-leave-active {
  position: absolute;
}

</style>
